<template>
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="860px"
        max-height="300"
        top="5vh"
        draggable
        append-to-body
        @closed="handleClosed">
        <el-form
            ref="formRef"
            :model="prizeFromParams"
            :rules="rules"
            label-width="140px"
            :disabled="dialogType.view"
            class="prize-form zw-common-scrollbar">
            <aside class="form-title">奖品设置</aside>
            <template v-for="(item, index) in formList" :key="index">
                <template v-if="item.type == 1">
                    <el-form-item :label="item.label" required>
                        <el-input
                            :model-value="rewardLevenMap[levenIndex]"
                            disabled
                            maxlength="15"
                            show-word-limit
                            placeholder="请输入标题名称" />
                    </el-form-item>
                </template>
                <template v-if="item.type == 2">
                    <el-form-item :label="item.label" :prop="item.prop" class="form-radio-item">
                        <el-radio-group v-model="prizeFromParams.reward_type" :disabled="disabled">
                            <el-radio :label="1">实物奖品</el-radio>
                            <el-radio :label="2">红包奖品</el-radio>
                        </el-radio-group>
                    </el-form-item>
                </template>
                <template v-if="item.type == 3">
                    <el-form-item :label="item.label" :prop="item.prop">
                        <el-input
                            v-model.trim="prizeFromParams.reward_title"
                            maxlength="20"
                            show-word-limit
                            placeholder="请输入奖品名称" />
                    </el-form-item>
                </template>
                <template v-if="item.type == 4">
                    <el-form-item :label="item.label" :prop="item.prop">
                        <single-upload
                            v-model="prizeFromParams[rewardImageKey[prizeFromParams.reward_type]]"
                            :default-image="defaultPrizeImage[prizeFromParams.reward_type]"
                            size="2048"
                            accept=".jpg,.png,.jpeg">
                            <template #tip> 支持jpg、jpeg、png格式图片，大小不超过2M，建议长宽比1:1 </template>
                        </single-upload>
                    </el-form-item>
                </template>
                <template v-if="item.type == 5">
                    <el-form-item v-show="prizeFromParams.reward_type === 1" :label="item.label" :prop="item.prop">
                        <!-- 新增页面进入 -->
                        <template v-if="!disabled">
                            <el-input-number
                                v-model="prizeFromParams.reward_stock"
                                :min="1"
                                :max="MAX_NUMBER"
                                :controls="false" />
                            <span> 个 </span>
                        </template>
                        <!-- 编辑页面 & 不是未开始的活动 进入 -->
                        <template v-else>
                            <el-input-number
                                :model-value="add(prizeFromParams.reward_stock, prizeFromParams.add_stock ?? 0)"
                                :min="1"
                                :controls="false"
                                disabled />
                            <span> 个, 原奖品</span>
                            <el-input-number v-model="prizeFromParams.reward_stock" :controls="false" disabled />
                            <span> 个, 追加奖品</span>
                            <el-input-number
                                v-model="prizeFromParams.add_stock"
                                :controls="false"
                                :min="0"
                                :max="subtract(MAX_NUMBER, prizeFromParams.reward_stock)" />
                            <span> 个 </span>
                        </template>
                    </el-form-item>
                </template>
                <template v-if="item.type == 6">
                    <el-form-item :label="item.label" :prop="item.prop">
                        <el-input-number
                            v-model="prizeFromParams.help_num"
                            :min="1"
                            :max="999"
                            :controls="false"
                            :disabled="disabled"
                            placeholder="请输入"
                            @input="handleChangeCheckHelpNum" />
                        <span> 人 </span>
                    </el-form-item>
                </template>
            </template>
            <!-- 实物奖品兑奖设置 -->
            <div v-show="prizeFromParams.reward_type === 1">
                <aside class="form-title">兑奖设置</aside>
                <redeem-prize-form
                    :edit="disabled"
                    :model="prizeFromParams"
                    :basic-date="formParams"
                    :file-list-limit="fileListLimit"
                    :reward-list="formParams.reward_list" />
            </div>

            <!-- 红包奖品 -->
            <div v-show="prizeFromParams.reward_type === 2">
                <el-form-item label="红包类型" prop="activity_name" class="form-radio-item">
                    <el-radio-group v-model="prizeFromParams.red_envelope_type" :disabled="disabled">
                        <el-radio :label="1">普通红包</el-radio>
                        <el-radio :label="2">拼手气红包</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="奖品数量" prop="reward_stock">
                    <!-- 新增页面进入 -->
                    <template v-if="!disabled">
                        <el-input-number
                            v-model="prizeFromParams.reward_stock"
                            :min="1"
                            :max="MAX_NUMBER"
                            :controls="false" />
                        <span> 个 </span>
                    </template>
                    <!-- 编辑页面 & 不是未开始的活动 进入 -->
                    <template v-else>
                        <el-input-number
                            :model-value="add(prizeFromParams.reward_stock, prizeFromParams.add_stock ?? 0)"
                            :min="1"
                            :controls="false"
                            disabled />
                        <span> 个, 原红包</span>
                        <el-input-number v-model="prizeFromParams.reward_stock" :controls="false" disabled />
                        <span> 个, 追加</span>
                        <el-input-number
                            v-model="prizeFromParams.add_stock"
                            :controls="false"
                            :min="0"
                            :max="subtract(MAX_NUMBER, prizeFromParams.reward_stock)" />
                        <span> 个 </span>
                    </template>
                </el-form-item>
                <el-form-item
                    v-show="prizeFromParams.red_envelope_type === 1"
                    label="单个红包金额"
                    prop="red_envelope_money">
                    <el-input-number
                        v-model="prizeFromParams.red_envelope_money"
                        :min="0.3"
                        :max="200"
                        :controls="false"
                        :disabled="disabled" />
                    <span> 元 </span>
                </el-form-item>
                <el-form-item
                    v-show="prizeFromParams.red_envelope_type === 2"
                    label="单个红包金额范围"
                    prop="red_envelope_money">
                    <el-input-number
                        v-model="prizeFromParams.red_envelope_money_min"
                        :min="0.3"
                        :max="200"
                        :controls="false"
                        :disabled="disabled" />
                    <span> ~ </span>
                    <el-input-number
                        v-model="prizeFromParams.red_envelope_range"
                        :min="prizeFromParams.red_envelope_money_min"
                        :controls="false"
                        :disabled="disabled" />
                    <span> 元 </span>
                </el-form-item>
                <el-form-item label="红包总金额" class="total-red-money form-radio-item">
                    <span> {{ Decimal.mul(prizeFromParams.red_envelope_money, computedTotalStock()) }} </span>
                    <span v-show="prizeFromParams.red_envelope_type === 2">
                        ~ {{ Decimal.mul(prizeFromParams.red_envelope_range, computedTotalStock()) }}
                    </span>
                    <span> 元 </span>
                </el-form-item>
                <el-form-item label="兑奖期限" class="exchange_date exchange_item" prop="exchange_time">
                    <el-date-picker
                        v-model="prizeFromParams.exchange_time"
                        type="datetimerange"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                        range-separator="—"
                        start-placeholder="开始时间"
                        end-placeholder="结束时间"
                        :default-time="defaultTime()"
                        :disabled-date="disabledDataFun">
                    </el-date-picker>
                    <el-tooltip
                        placement="top-start"
                        :width="270"
                        trigger="hover"
                        content="若未填写兑奖期限，则默认为永久有效">
                        <template #reference>
                            <span class="exchange_date_label">
                                <el-icon color="#ccc" size="16"><QuestionFilled /></el-icon>
                            </span>
                        </template>
                    </el-tooltip>
                </el-form-item>
                <el-form-item label="领奖须知">
                    <el-input
                        v-model="prizeFromParams.red_exchange_desc"
                        clearable
                        show-word-limit
                        placeholder="请保证获奖数据真实有效！"
                        rows="6"
                        type="textarea"
                        maxlength="500"
                        resize="none" />
                </el-form-item>
                <div class="money_rule">
                    <p class="explain">使用说明</p>
                    <p>使用红包之前请先前往【微信支付商户平台-商户平台-产品中心-付款到零钱-产品设置】中完成以下配置</p>
                    <p>1、【同一用户单日收款次数】调整为10次</p>
                    <p>2、【单日付款总数】调整为100000元</p>
                    <p>3、【同一用户收款额度】上限调整至200元</p>
                </div>
            </div>
        </el-form>
        <template #footer>
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitPrizeFrom"> 确认 </el-button>
        </template>
    </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, inject, computed, watch, nextTick } from 'vue';
import { cloneDeep, add, subtract, get } from 'lodash';
import { ElMessage, FormInstance } from 'element-plus';
import { useRoute } from 'vue-router';

import Decimal from 'decimal.js';
import { defaultTime } from '@/utils/utils';

import redeemPrizeForm from '../redeem-prize-form/redeem-prize-form.vue';
import singleUpload from './single-upload.vue';
import { installPrizeCheckRules, installPrizeValidator } from './check-rules';

import {
    MAX_NUMBER,
    DEFAULT_RED_EXCHANGE_DESC,
    DEFAULT_EXCHANGE_DESC,
    MONEY_MIN_NUMBER,
    MONEY_MAX_NUMBER,
    defautlExChangeDate
} from '../../utils/index';
import { IRewardRow, IPageType, IPrizeDialogType } from '../../utils/interface';
import { formParams } from '../../utils/paramsManager';
import fieldInfo from '../../utils/modules';

const route = useRoute();

const emit = defineEmits(['submit']);

const props = defineProps({
    type: {
        type: String,
        default: 'FISSION_DRAINAGE'
    },
    /** 进行中、结束的情况下禁用 */
    formDisabled: {
        type: Boolean,
        default: false
    }
});

const formList = fieldInfo[props.type].prizeInfo || [];

const pageType = reactive<IPageType>({
    look: route.query.type === 'look',
    edit: route.query.type === 'edit',
    new: route.query.type === 'new',
    copy: route.query.type === 'copy'
});

/** 表单详情返回的数据 */
// const formDetailInfo: any = inject('formDetailInfo');

/* ----------------------------表单禁用-start---------------------------- */

/**
 * 奖品弹窗打开的类型
 */
const prizeDialogType = ref<IPrizeDialogType>('add');

/** 用来给页面做逻辑判断的奖品弹窗类型的判断 */
const dialogType = computed(() => {
    return {
        add: prizeDialogType.value === 'add',
        edit: prizeDialogType.value === 'edit',
        view: prizeDialogType.value === 'view'
    };
});

/** 是否是编辑页面下 的 编辑奖品 */
const disabled = computed(() => {
    return dialogType.value.edit && props.formDisabled && pageType.edit && !prizeFromParams.value.is_add_reward;
});
/* ----------------------------表单禁用-end---------------------------- */

/**
 * 禁用当前开始的时间
 */
const disabledDataFun = (time: any) => {
    if (formParams.period_type === 2) {
        return time.getTime() < +new Date(formParams?.activity_time?.[0]) - (8.64e7 - 1);
    }
    return time.getTime() < Date.now() - 8.64e7;
};

/* ----------------------------奖品表单内容-start---------------------------- */
/**
 * 表单实例
 */
const formRef = ref<FormInstance>();
/**
 * @description 等级的索引，如果是新增则是数组长度,
 * 编辑和新增时都会使用这个东西，非常重要
 */
const levenIndex = ref(0);

/**
 * 默认的红包图片， 1: 实物，2: 红包
 */
const defaultPrizeImage = {
    1: '//static.scrm.keyid.cn/assets/images/web-pc/default-liwu.png',
    2: '//static.scrm.keyid.cn/assets/images/web-pc/default-hongbao.png'
};
/**
 * 图片的key,实物是reward_image，红包是reward_red_image
 */
const rewardImageKey = {
    1: 'reward_image',
    2: 'reward_red_image'
};
const rewardLevenMap = ['一级奖品', '二级奖品', '三级奖品', '四级奖品', '五级奖品'];

const defaultFromParams: IRewardRow = {
    reward_type: 1, // 1: 实物， 2: 红包
    reward_title: '',
    reward_image: defaultPrizeImage[1], // 是一段url
    reward_red_image: defaultPrizeImage[2], // 是一段url
    reward_stock: 1, // int 类型
    help_num: undefined, // int 类型
    red_exchange_desc: DEFAULT_RED_EXCHANGE_DESC,
    // > 红包类型
    red_envelope_type: 1, // 1: 普通， 2: 拼手气
    red_envelope_money: MONEY_MIN_NUMBER, // float 类型,
    exchange_desc: DEFAULT_EXCHANGE_DESC,
    // >> 拼手气红包
    red_envelope_total: 0, // float 类型
    red_envelope_money_min: MONEY_MIN_NUMBER, // 拼手气红包最小值
    red_envelope_range: MONEY_MAX_NUMBER, // 拼手气红包最大值
    //}
    // 兑换设置
    exchange_usage_type: 1, // 1: 兑换码, 2: 线下邮寄，
    exchange_code_type: 1, // 1: 系统自动生成, 2: 导入兑奖码，
    exchange_file_list: [],
    exchange_time: [],
    // >> 线下邮寄 时才有， 否则是 []
    mail_info: [],
    is_update: 1 //是否更新客户信息  1-关 2-开
};
const prizeFromParams = ref<IRewardRow>(cloneDeep(defaultFromParams));

const {
    checkStock,
    checkHelpNum,
    checkRequire,
    checkExChangeFileCode,
    checkExChangeDate,
    checkRedEnvelope,
    checkMailInfo
} = installPrizeValidator(installPrizeCheckRules(prizeFromParams, levenIndex));

const rules = reactive({
    reward_type: [{ required: true, message: '请选择奖品类型' }],
    reward_title: [{ required: true, message: '请输入奖品名称' }],
    reward_image: [{ required: true, message: '请输入奖品图片' }],
    reward_stock: [{ required: true, validator: checkStock }],
    help_num: [{ required: true, validator: checkHelpNum }],
    exchange_usage_type: [{ required: true, message: '请选择兑奖方式', validator: checkRequire }],
    exchange_code_type: [{ required: true, message: '请选择兑奖码方式', validator: checkRequire }],
    exchange_file_list: [{ required: true, validator: checkExChangeFileCode }],
    exchange_time: [{ validator: checkExChangeDate, trigger: 'blur' }],
    red_envelope_type: [{ required: true, message: '请选择红包类型' }],
    red_envelope_money: [{ required: true, validator: checkRedEnvelope }],
    mail_info: [{ required: true, validator: checkMailInfo }],
    is_update: [{ required: true, message: '请选择是否更新到客户上' }]
});

/**
 * 变换助力人数时随时校验
 */
const handleChangeCheckHelpNum = async () => {
    await nextTick();
    formRef.value?.validateField(['help_num']);
};

/* ----------------------------奖品表单内容-end---------------------------- */

/* ----------------------------弹窗显示隐藏-start---------------------------- */
const dialogVisible = ref(false);

// 弹窗标题
const dialogTitle = computed(() => {
    if (dialogType.value.edit) {
        return '编辑奖品';
    }
    if (dialogType.value.view) {
        return '查看奖品';
    }
    return '新建奖品';
});

/**
 * 弹窗关闭重置页面内容
 */
const handleClosed = async () => {
    prizeFromParams.value = cloneDeep(defaultFromParams);
    formRef.value?.resetFields();
};
/**
 * 手动打开弹窗的方法，传入奖品数据回显
 * @param prizeData 奖品数据
 */
const open = (prizeData: IRewardRow, index: number, dialogType: IPrizeDialogType = 'add') => {
    // 根据外部传来的类型。默认的是add。新增奖品
    prizeDialogType.value = dialogType;

    if (prizeData) {
        levenIndex.value = index;
        // 拼手气红包初始默认值
        if (prizeData.red_envelope_type === 2) {
            prizeData.red_envelope_money_min = prizeData.red_envelope_money;
            // 普通红包给默认值是0.3
            prizeData.red_envelope_money = MONEY_MIN_NUMBER;
        } else {
            // 拼手气红包最大值给默认值是200
            prizeData.red_envelope_range = MONEY_MAX_NUMBER;
        }

        // 红包的情况下给默认的奖品图
        if (prizeData.reward_type === 2) {
            prizeData.reward_red_image = prizeData.reward_image;
            prizeData.reward_image = defaultPrizeImage[1];
        } else {
            // 实物的情况下给红包默认的奖品图
            prizeData.reward_red_image = defaultPrizeImage[2];
        }
        Object.assign(prizeFromParams.value, prizeData);
    } else {
        levenIndex.value = formParams.reward_list.length;
        setFirstDefaultTime();
    }

    dialogVisible.value = true;
};

/**
 * 确认提交奖品内容，校验通过后触发submit事件
 */
const submitPrizeFrom = async () => {
    try {
        await formRef.value?.validate();

        const prizeParams = cloneDeep(prizeFromParams.value);

        // 过滤兑换码文件, 如果是 => 兑换码：系统自动生成 ｜ 兑换方式不为兑换码 ｜ 红包奖品
        // 则把兑换码文件清理掉
        if (
            prizeParams.exchange_code_type === 1 ||
            prizeParams.exchange_usage_type !== 1 ||
            prizeParams.reward_type === 2
        ) {
            prizeParams.exchange_file_list = [];
        }
        if (prizeParams.reward_type === 2) {
            // 过滤拼手气红包的字段
            if (prizeParams.red_envelope_type === 2) {
                if (prizeParams.red_envelope_money_min) {
                    prizeParams.red_envelope_money = prizeParams.red_envelope_money_min;
                }
                prizeParams.red_envelope_money_min = undefined;
            }

            // 红包的把image字段替换成后端需要的字段. 加  || '' 只是为了ts不报错.
            prizeParams.reward_image = prizeParams.reward_red_image || '';
        } else {
            prizeParams.reward_red_image = undefined;
        }

        // 调接口之前最好可以删除is_add_reward字段，不需要传给后端
        prizeParams.is_add_reward = dialogType.value.add;

        emit('submit', prizeParams, levenIndex.value);
        dialogVisible.value = false;
    } catch (err: any) {
        // 校验失败给出提示
        const [[errMessage]]: any = Object.values(err);
        ElMessage.warning({
            grouping: true,
            message: errMessage?.message,
            repeatNum: 1
        });
    }
};
/* ----------------------------弹窗显示隐藏-end---------------------------- */

/* ----------------------------默认时间-start---------------------------- */
/** 设置默认的时间 */
const setFirstDefaultTime = () => {
    // 新增状态下，设置了开始和结束时间,动态添加所有的兑奖时间
    const time = defautlExChangeDate(formParams.period_type, formParams.activity_time);
    if (!prizeFromParams.value.exchange_time?.length) {
        prizeFromParams.value.exchange_time = [...time];
    }
};
/* ----------------------------默认时间-end---------------------------- */

/* ----------------------------库存数量-start---------------------------- */
/** 计算总数库存， 在编辑的情况下会加上添加库存的数量。新增/复制的情况下 add_stock 为 undefined 或者 0  */
const computedTotalStock = () => {
    return add(prizeFromParams.value.reward_stock, prizeFromParams.value.add_stock ?? 0);
};

/** 追加库存上传文件限制 */
const fileListLimit = computed(() => {
    // 非编辑页面编辑奖品。则限制上传仍然是1条，
    if (!disabled.value) {
        return 1;
    }

    // 获取当前对应的奖品文件列表的数量 + 1。因限制的是每次只追加一条兑换码文件
    const length = get(formParams, `reward_list[${levenIndex.value}].exchange_file_list.length`, 0);
    return length + 1;
});

/* ----------------------------库存数量-end---------------------------- */

/* ----------------------------兑换码文件-start---------------------------- */
// 兑换码文件变更时，清除校验
watch(
    () => prizeFromParams.value.exchange_file_list,
    () => {
        formRef.value?.clearValidate(['exchange_file_list']);
    }
);
/* ----------------------------兑换码文件-end---------------------------- */

/* ----------------------------计算金额-start---------------------------- */
const computedEnvelopMonent = computed(() => {
    const { red_envelope_type, red_envelope_money_min, red_envelope_money }: any = prizeFromParams.value;
    const money = red_envelope_type === 2 ? red_envelope_money_min : red_envelope_money;
    return Decimal.mul(money, computedTotalStock());
});
/* ----------------------------计算金额-end---------------------------- */

defineExpose({
    open
});
</script>
<style lang="scss" scoped>
@mixin fz-m($fontSize: 16px) {
    font-family: PingFangSC-Medium, PingFang SC;
    font-size: $fontSize;
    font-weight: 500;
}
.form-title {
    display: flex;
    align-items: center;

    margin-bottom: 24px;

    color: #333333;

    @include fz-m;
    &::before {
        width: 3px;
        height: 16px;
        margin-right: 6px;

        content: '';

        border-radius: 2px;
        background-color: #ff6b00;
    }
}

:deep(.el-input) {
    width: 420px;
}

:deep(.el-input-number) {
    margin: 0 6px;
    width: 100px;
    &:first-child {
        margin-left: 0px;
    }
    .el-input__inner {
        text-align: left;
    }
}

.money_rule {
    padding: 16px;
    margin-top: 6px;
    height: 98px;
    border-radius: 4px;
    background-color: #fffaf9;
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    color: #585858;
    line-height: 20px;
    .explain {
        color: var(--el-color-primary);
    }
}

.total-red-money {
    font-size: 14px;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: var(--el-color-primary);
    line-height: 14px;
}

:deep(.el-form-item__label::before) {
    margin-right: 0px !important;
}

:deep(.prize-dialog) {
    line-height: 1;
    .el-dialog__body {
        padding: 24px;
        padding-right: 0px;
    }
}
.prize-form {
    max-height: 800px;
    height: 70vh;
    overflow-y: auto;
    padding-right: 24px;
    margin-right: -16px;
    .el-form-item {
        margin-bottom: 24px;
    }
    // el-radio的formitem边距
    .form-radio-item {
        margin-top: -8px;
        margin-bottom: 12px;
    }
}

.el-form-item {
    margin-bottom: 24px;
    .el-form-item {
        margin-bottom: 0;
    }
}
</style>
